﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataImporter.Models;
using System.Text.RegularExpressions;

namespace DataImporter.Modules
{
    public partial class ucQuestions : UserControl
    {
        #region Fields

        /// <summary>
        /// 数据列表
        /// </summary>
        private List<Category> categories = null;
        private List<HDAARM> hDAARMs = null;

        #endregion

        public ucQuestions()
        {
            InitializeComponent();
        }

        #region Methods

        /// <summary>
        /// 点击分析按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAnalyze_Click(object sender, EventArgs e)
        {
            if (ofdOpen.ShowDialog() != DialogResult.OK)
                return;
            var excels = ofdOpen.FileName.ToExcelList("附件1-2触摸屏问题计分表");
            hDAARMs = new List<HDAARM>();
            categories = new List<Category>();
            var parentId = 0;
            foreach (var excel in excels)
            {
                if (excel.H == "y")
                    parentId = 0;
                var categoryId = 0;
                if (!excel.G.IsNullOrEmpty())
                {
                    categoryId = this.categories.Find(c => c.Name == excel.G)?.Id ?? 0;
                    if (categoryId < 1)
                        this.categories.Add(new Category
                        {
                            Id = categoryId = this.categories.Count + 1,
                            Name = excel.G,
                        });
                }
                if (excel.A.IsNullOrEmpty())
                    continue;
                hDAARMs.Add(new HDAARM
                {
                    Id = hDAARMs.Count + 1,
                    Code = excel.A,
                    Name = excel.B,
                    Order = (hDAARMs.Count + 1) * 5,
                    Rule = excel.E,
                    ParentId = excel.D.IsNullOrEmpty() ? parentId : hDAARMs.Find(c => c.Code == excel.D).Id,
                    Remark = excel.F,
                    Radio = excel.I.Equals("y", StringComparison.OrdinalIgnoreCase),
                    Category = categoryId,
                    QuestionId = parentId,
                    CategoryName = excel.G,
                    Score = excel.C.IsNullOrEmpty() ? 0 : int.Parse(excel.C)
                });
                if (excel.H == "y")
                    parentId = hDAARMs.Last().Id;
            }
            this.dgvData.DataSource = null;
            this.dgvData.DataSource = hDAARMs;
        }

        /// <summary>
        /// 处理推荐
        /// </summary>
        /// <param name="recommanded">要处理的推荐内容</param>
        /// <returns>结果</returns>
        private string HandleRecommanded(string recommanded)
        {
            return Regex.Replace(Regex.Replace(recommanded.Trim().Trim('\t', '。').TrimStart('£', '*', '¨'), "[¨£*]", "，"), "（\\d+）", "");
        }

        /// <summary>
        /// 点击保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var db = new DBContext();
                db.CategoryDB.AsSugarClient().DbMaintenance.TruncateTable<HDAARM>();
                db.CategoryDB.AsSugarClient().DbMaintenance.TruncateTable<Category>();
                db.CategoryDB.InsertRange(categories.ToArray());
                if (db.HDAARMDB.InsertRange(hDAARMs.ToArray()))
                    MessageBox.Show("保存成功");
                else
                    MessageBox.Show("保存失败");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetAllData_Click(object sender, EventArgs e)
        {
            try
            {
                this.dgvData.DataSource = null;
                this.dgvData.DataSource = new DBContext().HDAARMDB.GetList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 点击删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            if (this.dgvData.SelectedRows?.Count == 0)
                return;
            if (MessageBox.Show("确定要删除吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                return;
            var ids = this.dgvData.SelectedRows.OfType<DataGridViewRow>().Select(c => (dynamic)c.Cells["Id"].Value).ToArray();
            if (new DBContext().HDAARMDB.DeleteByIds(ids))
            {
                this.btnGetAllData_Click(null, null);
            }
        }

        /// <summary>
        /// 点击检查按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (ofdOpen.ShowDialog() != DialogResult.OK)
                return;
            var excels = ofdOpen.FileName.ToExcelList("附件1-2触摸屏问题计分表");
            var ss = new StringBuilder();
            excels.ForEach(c =>
            {
                try
                {
                    if (!c.E.IsNullOrEmpty())
                        DyncmicRuntime.Compute(c.E.Replace("age", "18"));
                }
                catch
                {
                    ss.AppendLine($"编码：{c.A} 规则无法通过运算：{c.E}");
                }
            });
            this.rtbContent.Text = ss.ToString();
        }

        /// <summary>
        /// 点击获取所有分类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAllCategories_Click(object sender, EventArgs e)
        {
            this.categories = new DBContext().CategoryDB.GetList();
            this.dgvData.DataSource = null;
            this.dgvData.DataSource = this.categories;
        }

        #endregion
    }
}
